package util.gui;

import java.util.ArrayList;
import org.newdawn.slick.Font;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import util.gui.event.ActionEvent;
import util.gui.event.ActionEventListener;
import util.resource.ResourceManager;

public class Button extends Component implements ActionEvent
{
	protected Font font;
	protected String text;
	protected String actionCommand;
	private ArrayList<ActionEventListener> listeners=new ArrayList<ActionEventListener>();
	
	public Button(String text)
	{
		super();
		this.text=text;
		actionCommand=text;
		font=ResourceManager.getFont("guiFont");
		
		super.setMinHeight(font.getLineHeight());
		super.setMinWidth(getMinHeight());
		super.setWidth(font.getWidth(text)+2*LookAndFeel.borderSize);
		super.setHeight(font.getHeight(text)+2*LookAndFeel.borderSize);
		super.drawBorder=true;
	}
	
	public Button()
	{
		this("");
	}
	
	public void render(GameContainer gc,Graphics g,int x,int y)
	{
		Input i=gc.getInput();
		
		if(mouseCheck(g,i,x,y))
		{
			if(i.isMousePressed(Input.MOUSE_LEFT_BUTTON))
				buttonDown(); //TODO: Actually make this work properly on mouse release
			if(i.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON))
				super.backgroundColor=LookAndFeel.selected;
			else
				super.backgroundColor=LookAndFeel.mouseOverColor;
		}
		else
			super.backgroundColor=LookAndFeel.unselectColor;

		super.render(gc,g,x,y);
		
		g.setColor(LookAndFeel.textColor);
		g.setFont(font);
		g.drawString(text,x+LookAndFeel.borderSize,y+LookAndFeel.borderSize);
	}
	
	/**
	 * Called whenever the button is pressed.
	 */
	protected void buttonDown()
	{
		for(ActionEventListener ael: listeners)
			ael.ActionPerformed(this);
	}

	public String getActionCommand()
	{
		return actionCommand;
	}
	
	/**
	 * Adds a class to be notified of changes to this component.
	 * @param ael - class to be notified.
	 */
	public void addActionListener(ActionEventListener ael)
	{
		listeners.add(ael);
	}
}